package com.diankangwo.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//import com.alibaba.fastjson.JSONObject;

/**
 * 生成和解析二维码
 * 
 * @author Mr.zhu
 *
 */
public class QRCoderUtil {

	private int width;
	private int height;
	private String format;

	public QRCoderUtil() {
		Properties prop = LoadPropertyUtil.loadProperty("qrcode.properties");
		this.width = Integer.parseInt((String) prop.get("width"));
		this.height = Integer.parseInt((String) prop.get("height"));
		this.format = prop.get("format").toString();
	}

	/**
	 * 生成二维码流
	 * 
	 * @param content
	 *            要转化的内容数据
	 * @param response
	 *            HttpServletResponse
	 * @throws WriterException
	 * @throws IOException
	 */
	public void encoderQRCoder(String content, HttpServletResponse response) throws WriterException, IOException {
		// JSONObject json = new JSONObject();
		// json.put("zxing",
		// "https://github.com/zxing/zxing/tree/zxing-3.0.0/javase/src/main/java/com/google/zxing");
		// json.put("author", "zxing");
		// content = json.toString();
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
		MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream()); // 输出二维码
	}

	/**
	 * 生成二维码图片
	 * 
	 * @param content
	 *            二维码内容
	 * @param filePath
	 *            二维码存放路径
	 * @return 二维码地址
	 * @throws WriterException
	 */
	public String encoderQRCoderFile(String content, String filePath) throws WriterException {
		try {
			File file = new File(filePath);
			if (!file.exists() && !file.isDirectory()) {
				try {
					file.mkdir();
				} catch (Exception e) {
					System.out.println("二维码目录创建失败！");
					e.printStackTrace();
				}
			}
			String fileName = System.currentTimeMillis() + "." + format;
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			hints.put(EncodeHintType.MARGIN, 1);
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
			Path path = FileSystems.getDefault().getPath(filePath, fileName);
			MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
			return path.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 解析二维码
	 * 
	 * @param file
	 * @return 解析后的二位码数据;解析失败则返回null
	 */
	public String decoderQRCode(File file) {
		String filePath = file.getPath();
		BufferedImage image;
		try {
			image = ImageIO.read(new File(filePath));
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result = new MultiFormatReader().decode(binaryBitmap, hints); // 对图像进行解码

			// JSONObject content = JSONObject.parseObject(result.getText());
			// System.out.println("图片中内容： ");
			// System.out.println("author： " + content.getString("author"));
			// System.out.println("zxing： " + content.getString("zxing"));
			// System.out.println("图片中格式： ");
			// System.out.println("encode： " + result.getBarcodeFormat());
			return result.getText();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (NotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

}
